﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


//参考 ：https://blog.csdn.net/yrwan95/article/details/82194473
//
namespace UcToMP3
{
    public partial class Form1 : Form
    {
        private delegate void SetTextDelegate(string  msgText,int Val);
        public Form1()
        {
            InitializeComponent();
        }

        private void BtnSelect_Click(object sender, EventArgs e)
        {
            if (ChbBat.Checked) {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    string dirPath = fbd.SelectedPath;
                    TbxFilePath.Text = dirPath;
                    BtnConvert.Enabled = true;
                }
            }
            else
            {
                OpenFileDialog openDlg = new OpenFileDialog();
                openDlg.Filter = "网易音乐缓存文件|*.uc";
                if (openDlg.ShowDialog() == DialogResult.OK)
                {
                    TbxFilePath.Text = openDlg.FileName;
                    RtbDetial.Text += "打开文件：" + openDlg.FileName + "\r\n";
                    BtnConvert.Enabled = true;
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        { 
            this.Size = new Size(650, this.Height-RtbDetial.Height);
            PbCtrl.Visible = false;
            LabPbValue.Visible = false;
            RtbDetial.Visible = false;
            BtnConvert.Enabled = false;
            this.MinimumSize = this.Size;
            this.MaximumSize = this.Size;
         
        }

        private void BtnConvert_Click(object sender, EventArgs e)
        {
            if (ChbBat.Checked) {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    string saveDir = fbd.SelectedPath;
                    string[] filePaths=Directory.GetFiles(TbxFilePath.Text,"*.uc",SearchOption.AllDirectories);
                    if (filePaths.Length > 0)
                    {
                        RtbDetial.Text += "文件存储目录：" + saveDir + "\r\n";
                        LabPbValue.Visible = true;
                        PbCtrl.Visible = true;
                        Invoke(new SetTextDelegate(SetText), "获取要转换的文件，一共；" + filePaths.Length.ToString(), 0);
                        int fcnt = filePaths.Length;
                        for (int i=0;i<fcnt;i++)
                        {
                            string path = filePaths[i];
                            int start = path.LastIndexOf("\\") + 1;
                            string fileName = path.Substring(start);
                            string savePath = saveDir + "\\" + fileName.Replace(".uc", ".mp3");
                            ConvertToMp3(path, savePath);
                            int pbv = (i+1)*100/ fcnt;
                            Invoke(new SetTextDelegate(SetText), "已转换->"+(i+1).ToString()+"/" + filePaths.Length.ToString(), pbv);

                        }
                    }
                    else
                    {
                        RtbDetial.Text += "没有获取到要转换的数据。\r\n";
                    }
                }
            }
            else
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "MP3文件|*.mp3";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string savepath = saveFileDialog.FileName;
                    RtbDetial.Text += "文件存储位置：" + saveFileDialog.FileName + "\r\n";
                    LabPbValue.Visible = true;
                    PbCtrl.Visible = true;
                    ConvertToMp3(TbxFilePath.Text, savepath);
                    MessageBox.Show("数据转换完成");
                }
            }
        }


        private void ConvertToMp3(string sourcePath, string targetPath)
        {
            FileStream fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
            long n = fs.Length;
            byte[] byts = new byte[n];
            int cnt, m;
            m = 0;
            cnt = fs.ReadByte();
            while (cnt != -1)
            {
                byts[m++] = Convert.ToByte(cnt); 
                cnt = fs.ReadByte();
            }
            Invoke(new SetTextDelegate(SetText), "文件读取完毕，开始转换；",33);
            for (int i = 0; i < byts.Length; i++)
            {
                byts[i] ^= 0xa3;
            }
            Invoke(new SetTextDelegate(SetText), "文件转换完毕，开始写入；",70);
            FileStream writer = new FileStream(targetPath,FileMode.Create,FileAccess.Write);
            writer.Write(byts,0,byts.Length);
            writer.Flush();
            writer.Close();
            fs.Flush();
            fs.Close();
            Invoke(new SetTextDelegate(SetText), "文件写入完毕。",100);
        }

        private void BtnDetial_Click(object sender, EventArgs e)
        {
            if (RtbDetial.Visible) {
                RtbDetial.Visible = false;
                this.Size = new Size(650, this.Height - RtbDetial.Height);
                this.MinimumSize = new Size(650, this.Height - RtbDetial.Height);
                this.MaximumSize = new Size(650, this.Height - RtbDetial.Height);
            }
            else
            {
                RtbDetial.Visible = true;
                this.Size = new Size(650, this.Height + RtbDetial.Height);
                this.MinimumSize = new Size(650, this.Height + RtbDetial.Height);
                this.MaximumSize = new Size(650, this.Height + RtbDetial.Height);
            }
        }

        public void SetText(string info,int vals)
        {
            if (RtbDetial.Text.Length > 100 * 1024)
            {
                RtbDetial.Text = "";
            }
            PbCtrl.Value = vals;
            LabPbValue.Text = PbCtrl.Value.ToString() + "%";
            RtbDetial.AppendText(string.Format("[{0}]:{1} \r\n", DateTime.Now.ToLongTimeString(), info));
            RtbDetial.Focus();//获取焦点
            RtbDetial.Select(RtbDetial.TextLength, 0);//光标定位到文本最后
            RtbDetial.ScrollToCaret();//滚动到光标处
        }
    }
}
